import React, { FC, useState } from "react"
import useLoadQuestionData from "../../../hooks/useLoadQuestionData"
import { Button, Result, Spin } from "antd"
import useGetPageInfo from "../../../hooks/useGetPageInfo"
import { useNavigate } from "react-router-dom"
import { useTitle } from "ahooks"
import styles from "./index.module.scss"
import StatHeader from "./c-cpns/StatHeader"
import ComponentList from "./c-cpns/ComponentList"
import PageStat from "./c-cpns/PageStat"
import ChartStat from "./c-cpns/ChartStat"

const Stat: FC = () => {
    const nav = useNavigate()

    const { loading } = useLoadQuestionData()

    const { title, isPublished } = useGetPageInfo()

    // 状态提升：selectedId type（父组件管理数据，传递个子组件使用）
    const [selectedComponentId, setSelectedComponentId] = useState("")
    const [selectedComponentType, setSelectedComponentType] = useState("")

    // 修改标题
    useTitle(`问卷统计 - ${title}`)

    // loading效果
    const LoadingElem = (
        <div style={{ textAlign: "center", marginTop: "60px" }}>
            <Spin />
        </div>
    )

    // Content Elem
    function genContentElem() {
        // 初始值为undefined，从服务端获取布尔值，如果直接初始化为false，就出现了页面闪烁的现象
        if (typeof isPublished === "boolean" && !isPublished) {
            return (
                <div style={{ flex: "1" }}>
                    <Result
                        status="warning"
                        title="该问卷尚未发布"
                        extra={
                            <Button type="primary" onClick={() => nav(-1)}>
                                返回
                            </Button>
                        }
                    />
                </div>
            )
        }

        return (
            <>
                <div className={styles.left}>
                    <ComponentList
                        selectedComponentId={selectedComponentId}
                        setSelectedComponentId={setSelectedComponentId}
                        setSelectedComponentType={setSelectedComponentType}
                    />
                </div>
                <div className={styles.main}>
                    <PageStat
                        selectedComponentId={selectedComponentId}
                        setSelectedComponentId={setSelectedComponentId}
                        setSelectedComponentType={setSelectedComponentType}
                    />
                </div>
                <div className={styles.right}>
                    <ChartStat selectedComponentId={selectedComponentId} selectedComponentType={selectedComponentType} />
                </div>
            </>
        )
    }

    return (
        <div className={styles.container}>
            <div>
                <StatHeader />
            </div>
            <div className={styles["content-warpper"]}>
                {loading && LoadingElem}
                {!loading && <div className={styles.content}>{genContentElem()}</div>}
            </div>
        </div>
    )
}

export default Stat
